

//
//  EmoticonManager.swift
//  HotNews
//
//  Created by yang on 2017/11/5.
//  Copyright © 2017年 成品家（北京）网路科技有限公司. All rights reserved.
//

import Foundation

class EmoticonManager
{
    static let shared = EmoticonManager()
    
    //表情包数组的懒加载
    lazy var packages = [YYYEmoticonPackageModel]()
    
    //构造函数
    private init() {
        //加载包数据
        loadPackageData()
    }
    
    //懒加载加载bundle
    lazy var bundle: Bundle = {
        let path = Bundle.main.path(forResource: "HMEmoticon.bundle", ofType: nil)
        let bundle = Bundle(path: path!)
        return bundle!
    }()
}

//添加最近使用的表情
extension EmoticonManager
{
    func addRecentEmoticons(em: YYYEmoticonModel)
    {
        //设置最近表情的使用次数加1
        em.times += 1
        //判断表情包中是否包含有当前选中的表情，没有记录进行添加
        var emoticons = packages[0].emoticons
        if !emoticons.contains(em)
        {
            emoticons.append(em)
        }
        //添加到表情包中的表情进行降序排序
        //闭包只有一个返回值，参数可以省略
        emoticons.sort
        {
            $0.times > $1.times
        }
        
//        emoticons.sort {
//            return $0.times > $1.times
//        }
//        emoticons.sort { (em1, em2) -> Bool in
//            return em1.times > em2.times
//        }
        //当表情包中的记录数大于20，删除最后一个表情
        if emoticons.count > 20
        {
            emoticons.removeSubrange(20..<emoticons.count)
        }
        packages[0].emoticons = emoticons
    }
}
//表情字符串的处理
extension EmoticonManager
{
    /// 表情文本
    ///
    /// - Parameter string: 目标字符串
    /// - Returns: 属性文本 （图文混排）
    func emoticonString(string: String, font: UIFont) -> NSMutableAttributedString
    {
        let attributedString = NSMutableAttributedString(string: string)
        
        //设置匹配项 ()、[]在正则表达式中都是关键字
        //[哈哈]，[]匹配表情
        let pattern = "\\[.*?\\]"
        
        //创建正则表达式
        guard let regx = try? NSRegularExpression(pattern: pattern, options: []) else
        {
            return attributedString
        }
        //匹配所有项
        let matches = regx.matches(in: string, options: [], range: NSRange(location: 0, length: attributedString.length))
        //反序遍历
        for m in matches.reversed()
        {
            let range = m.range(at: 0)
            let subString = (string as NSString).substring(with: range)
            print(subString)
            
            //通过[哈哈]查找对应的表情模型
            if let em = findEmoticons(string: subString)
            {
                attributedString.replaceCharacters(in: range, with: em.imageText(font: font))
            }
        }
        //统一设置字体属性
       
        //设置字体大小
        attributedString.addAttributes([NSAttributedStringKey.font: font], range: NSRange(location: 0, length: attributedString.length))
        
        //设置字体颜色
        attributedString.addAttributes([NSAttributedStringKey.foregroundColor: UIColor.darkGray], range: NSRange(location: 0, length: attributedString.length))
        return attributedString
    }
    
    
    /// 查找表情
    ///
    /// - Parameter string: 表情字符串 [哈哈]
    /// - Returns: 表情模型
    func findEmoticons(string: String) -> YYYEmoticonModel?
    {
        for p in packages
        {
            let result = p.emoticons
//            let filterResult = result.filter({ (em) -> Bool in
//                return em.chs == string
//            })
            //尾随闭包的三种写法
            //写法1 尾随闭包
//            let filterResult = result.filter(){ (em) -> Bool in
//                return em.chs == string
//            }
            //写法2，参数用$0、$1依次类推
//            let filterResult = result.filter(){
//                return $0.chs == string
//            }
            //写法3 return可以省略
            let filterResult = result.filter(){
                $0.chs == string
            }
            if filterResult.count == 1
            {
                return filterResult[0]
            }
        }
        return nil
    }
}
private extension EmoticonManager
{
    //加载包数据
    func loadPackageData()
    {
        guard let path = Bundle.main.path(forResource: "HMEmoticon.bundle", ofType: nil),
              let bundle = Bundle(path: path),
              let emoticonPath = bundle.path(forResource: "emoticons.plist", ofType: nil),
              let emoticonArray = NSArray(contentsOfFile: emoticonPath) as? [[String: String]],
              let modelsArray = NSArray.yy_modelArray(with: YYYEmoticonPackageModel.self, json: emoticonArray) as? [YYYEmoticonPackageModel] else
        {
            return
        }
        //使用 += 不会再次给packages分配空间，直接追加数据
        packages += modelsArray
    }
}
